from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from api.database import Base

class User(Base):
    """
    用户模型
    """
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False) # String 长度明确
    email = Column(String(255), unique=True, index=True, nullable=False)  # String 长度明确
    hashed_password = Column(Text, nullable=False)  # 使用Text以兼容所有数据库（加密后的密码）
    full_name = Column(String(100), nullable=True) # String 长度明确
    is_active = Column(Boolean, default=True)
    is_admin = Column(Boolean, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    mfa_secret = Column(String(255), nullable=True) # String 长度明确
    is_mfa_enabled = Column(Boolean, default=False)
    # 硬件密钥相关字段
    webauthn_credential_id = Column(Text, nullable=True)  # WebAuthn凭证ID
    webauthn_public_key = Column(Text, nullable=True)  # 公钥
    webauthn_sign_count = Column(Integer, default=0)  # 签名计数器
    is_webauthn_enabled = Column(Boolean, default=False)  # 是否启用硬件密钥
    avatar = Column(String(500), nullable=True)  # URL可能较长，String 长度明确
    delete_time = Column(DateTime(timezone=True), nullable=True)
    default_translation_config_id = Column(Integer, nullable=True)  # 默认翻译配置ID
    email_accounts = relationship("EmailAccount", back_populates="user")
    proxies = relationship("Proxy", back_populates="user")
    translation_configs = relationship("TranslationConfig", back_populates="user")
